﻿using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using Raven.Client;

namespace Udbjorg.Net.Logic.Raven
{
    public class RavenApiController : ApiController
    {
        public IDocumentSession DocumentSession { get; set; }
        public override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {
            DocumentSession = DocumentStore.Instance.OpenSession();
            return base.ExecuteAsync(controllerContext, cancellationToken).ContinueWith(task=>
                                                                                            {
                                                                                                using(DocumentSession)
                                                                                                {
                                                                                                    if (DocumentSession != null && task.Status == TaskStatus.Faulted)
                                                                                                        DocumentSession.SaveChanges();
                                                                                                }
                                                                                                    return task;
                                                                                            }).Unwrap();
        }

       
    }
}
